# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
from douban.settings import mysql_db_name, mysql_host, mysql_user, mysql_password
import pymysql.cursors


class DoubanPipeline(object):
    def __init__(self):
        # 连接数据库
        self.connect = pymysql.connect(
            host=mysql_host,
            db=mysql_db_name,
            user=mysql_user,
            password=mysql_password,
            charset='utf8',
            use_unicode=True
        )
        # 通过cursor执行增删改查
        self.cursors = self.connect.cursor()

    def process_item(self, item, spider):
        try:
            # 插入sql
            self.cursors.execute("""
                insert into scrapy_movies(serial_number, introduce, star, evaluate, describle, image) values (%s,%s,%s,%s,%s,%s)
            """, (
                item['serial_number'],
                item['introduce'],
                item['star'],
                item['evaluate'],
                item['describle'],
                item['image']
            ))
            # 提交sql
            self.connect.commit()

        except Exception as error:
            print(error)
        return item
